<template>
    <el-card class="box-card">
        <template #header>
            <div class="card-header">
                <span>管理相册</span>
                <el-button class="button" type="primary" :icon="Plus" @click="addalbm">新增相册</el-button>
            </div>
        </template>
        <div class="max-h-[32rem] h-[32rem] w-full flex flex-wrap overflow-scroll">
            <el-card class="w-[24%] h-2/5 m-1" v-for="item in imgalbmlist" :key="item.id">
                <template #header>
                    <div class="card-header">
                        <span>{{ item.name }}</span>
                        <el-dropdown trigger="click">
                            <span class="el-dropdown-link">
                                <el-icon class="el-icon--right">
                                    <arrow-down />
                                </el-icon>
                            </span>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item @click="gotophotolist(item)">查看相册</el-dropdown-item>
                                    <el-dropdown-item @click="emitimgalbm(item)">编辑相册</el-dropdown-item>
                                    <el-dropdown-item @click="delectalbm(item)">删除相册</el-dropdown-item>
                                </el-dropdown-menu>
                            </template>

                        </el-dropdown>
                    </div>
                </template>
                <div class="h-4/5 w-full">
                    <el-image style="width: 100%; height:110px;" :src="item.amblecover" :preview-src-list="srcList"
                        fit="cover" hide-on-click-modal :preview-teleported="true" lazy>
                        <template #error>
                            <div class="image-slot">
                                <el-icon><icon-picture /></el-icon>
                            </div>
                        </template>
                    </el-image>
                </div>
            </el-card>


        </div>
        <dialogg :istoshow="showdialog" :title="emitimg.title ? emitimg.title : '添加相册'" @cansol="cansol" width="32%">
            <template #body>
                <el-form :model="emitimg" width="20%" ref="addref" :rules="rules">
                    <el-form-item label="名字" label-width="70px" prop="name">
                        <el-input v-model="emitimg.name" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="描述" label-width="70px" prop="description">
                        <el-input v-model="emitimg.description" :rows="2" type="textarea" placeholder="请输入" maxlength="60"
                            resize="vertical" show-word-limit />
                    </el-form-item>
                    <el-form-item label="封面" label-width="70px" prop="image">
                        <upload :height="100" :width="100" :multiple="false" :limit="1" v-model:imglist="imagelist">
                        </upload>
                    </el-form-item>
                </el-form>
            </template>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="cansol">取消</el-button>
                    <el-button type="primary" @click="subandclose(addref)">
                        保存
                    </el-button>
                </span>
            </template>
        </dialogg>
        <pagination :currentPage="allcurrentPage" :pageSize="allpageSize" :total="alltotal" :loading="loading"
            @updatepage="Allchangepage"></pagination>
    </el-card>
</template>
 
<script setup>
import { useBaseStore } from "@/store/Base.js"
import dialogg from '@/components/dialog.vue'
import upload from '@/components/upload.vue'
import { ref, reactive, onMounted, inject } from 'vue'
import { useRouter } from 'vue-router'
import {
    Plus,
    ArrowDown,
    Picture as IconPicture
} from '@element-plus/icons-vue'
import { addaumble, editaumble, submitFileName, getaumble, getcount, delectaumbles } from "@/api/photo.js"
import { getQiniuToken } from "@/api/users.js"
import { uploadqiniu } from "@/util/index.js"
let baseStore = useBaseStore()
let router = useRouter()
let reload = inject('reload')
let addref = ref(null)
let isadd = false
/* 相册编辑或者添加的数据 */
let showdialog = ref(false)
let emitimg = reactive({
    name: "",
    description: "",

})
/* 分页器的数据或者函数 */
const allcurrentPage = ref(1)
const allpageSize = ref(6)
const alltotal = ref(0)
let loading = ref(false)
async function Allchangepage(val) {
    allcurrentPage.value = val;
    await getaumbles()
}
let imagelist = ref([])
const srcList = ref([])
/* 相册的数据结构 */
let imgalbmlist = ref([
    
])
/* 新增相册 */
function addalbm() {
    reset()
    isadd = true
    showdialog.value = true
}
/* 获取信息 */
async function getaumbles() {
    let ress = getcount()
    let res = getaumble({
        page: allcurrentPage.value,
        pageSize: allpageSize.value,
    })
    let result = await Promise.all([res, ress])
    let data = result?.map((item) => {
        return item.data.data
    })
    alltotal.value = data[1].count
    if (alltotal.value !== 0) {
        imgalbmlist.value = data[0].data?.map(item => {
            srcList.value.push(item.album_cover)
            return {
                id: item.id,
                name: item.album_name,
                description: item.description,
                amblecover: item.album_cover
            }
        })
    }else{
        ElMessage({
            message: '暂无数据',
            type: 'warning',
        })
    }
}
onMounted(async () => {
    await getaumbles()
})
/* 删除相册 */
async function delectalbm(data) {
    let res = await delectaumbles({
        aumble_id: data.id
    })
    if (res.data.status == 200) {
        ElMessage({
            message: '删除成功',
            type: 'success',
        })
        
    } else {
        ElMessage({
            message: '删除失败',
            type: 'warning',
        })
    }
    reload()
}
/* 编辑相册 */
function emitimgalbm(item) {
    emitimg.name = item.name
    emitimg.description = item.description
    emitimg.title = "编辑" + "-" + emitimg.name
    imagelist.value = [{
        url: item.amblecover,
        name: "封面",
    }]
    showdialog.value = true
}
/* 查看相册列表 */
function gotophotolist(data) {
    console.log(data);
    router.push({
        path: "/pic/piclist",
        query: {
            id: data.id,
            name: data.name
        }
    })
}
/* 取消提交相册 修改 或者 添加 */
function cansol() {
    isadd = false
    showdialog.value = false
}
function reset() {
    emitimg.name = ""
    emitimg.title = ""
    emitimg.amblecover = ""
    emitimg.description = ""
    imagelist.value = []
    showdialog.value = false
}
/* 表单校验规则 */
let rules = reactive({
    name: [
        {
            required: true,
            message: '不能为空',
            trigger: 'blur',
        },
    ],
    description: [
        {
            required: true,
            message: '不能为空',
            trigger: 'blur',
        },
    ],
})
/* 编辑或者添加相册的非空校验 */
async function subandclose(dialogRef) {
    if (!dialogRef) return;
    await dialogRef.validate(async (valid, fields) => {
        if (valid) {
            if (!isadd) {
                /* 编辑 */
                /* 参数校验通过 获取七牛云的token */
                let cover = ''
                if (imagelist.value[0].hasOwnProperty("raw")) {
                    let data = await getQiniuToken();
                    if (data.data.status == 200) {
                        baseStore.qiniuToken = data.data.data.uploadToken;
                        let Checkuploadlist = await uploadqiniu(imagelist.value)
                        if (Checkuploadlist[0].status == 200) {
                            cover = import.meta.env.VITE_API_PHOTO + Checkuploadlist[0].data.key
                        }
                    }
                }
                let res = await editaumble({
                    id: emitimg.id,
                    name: emitimg.name,
                    description: emitimg.description,
                    album_cover: cover,
                })
                if (res.data.status == 200) {
                    ElMessage({
                        message: '修改成功',
                        type: 'success',
                    })
                    reset()
                    reload()
                }
            } else {
                /* 添加 */
                let res = await addaumble({
                    album_name: emitimg.name,
                    description: emitimg.description,
                })
                if (res.data.status == 200) {
                    /* 上传封面 */
                    /* 参数校验通过 获取七牛云的token */
                    let data = await getQiniuToken();
                    if (data.data.status == 200) {
                        baseStore.qiniuToken = data.data.data.uploadToken;
                        let aumble_id = res.data.data.id
                        let Checkuploadlist = await uploadqiniu(imagelist.value)
                        if (Checkuploadlist[0]?.status == 200) {
                            /* 上传文件成功 添加文件名字给后端*/
                            let ok = await submitFileName({
                                aumble_id,
                                file_name: import.meta.env.VITE_API_PHOTO + Checkuploadlist[0].data.key
                            })
                            if (ok.data.status == 200) {
                                ElMessage({
                                    message: '上传成功',
                                    type: 'success',
                                })
                                reset()
                                reload()
                            }
                        }
                    }
                } else {
                    ElMessage({
                        message: '添加失败',
                        type: 'warning',
                    })
                    reset()
                }
            }
        } else {
            ElMessage({
                message: '请填写信息',
                type: 'warning',
            })
        }
    })

}

</script>

<style lang="css" scoped>
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

:deep(.el-card__header) {
    padding: 5px 15px !important;
}
</style>